package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;

import model.TrainWay;
import dao.TrainWayDAO;

public class TrainWayDAOImpl implements TrainWayDAO {
	DBUtil dbu = new DBUtil();
	Connection conn = null;
	PreparedStatement pstat = null;
	ResultSet rs = null;
	public List<TrainWay> getAll() {
		List<TrainWay> list = new ArrayList<TrainWay>();
		try {
			conn = dbu.getConnection();
			String sql = "select * from trainway";
			pstat = conn.prepareStatement(sql);
			rs = pstat.executeQuery();
			while (rs.next()) {
				TrainWay tw = new TrainWay();
				tw.setId(rs.getInt("ID"));
				tw.setWayname(rs.getString("WAYNAME"));
				list.add(tw);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbu.closeConnection(conn, pstat, rs);
		}
		return list;
	}

	public TrainWay getById(int id) {
		TrainWay tw=null;
		try {
			conn = dbu.getConnection();
			String sql = "select * from trainway where id=?";
			pstat = conn.prepareStatement(sql);
			pstat.setInt(1, id);
			rs = pstat.executeQuery();
			while (rs.next()) {
				tw = new TrainWay();
				tw.setId(rs.getInt("ID"));
				tw.setWayname(rs.getString("WAYNAME"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbu.closeConnection(conn, pstat, rs);
		}
		return tw;
	}

	public TrainWay getByName(String name) {
		TrainWay tw=null;
		try {
			conn = dbu.getConnection();
			String sql = "select * from trainway where WAYNAME=?";
			pstat = conn.prepareStatement(sql);
			pstat.setString(1, name);
			rs = pstat.executeQuery();
			while (rs.next()) {
				tw = new TrainWay();
				tw.setId(rs.getInt("ID"));
				tw.setWayname(rs.getString("WAYNAME"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbu.closeConnection(conn, pstat, rs);
		}
		return tw;
	}

}
